import axios from 'axios'
import {MessageBox,Loading } from 'element-ui';
axios.defaults.baseURL= window.server.SERVER_API
axios.defaults.timeout = 10000
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'//application/x-www-form-urlencoded;multipart/form-data;
// 请求拦截器
axios.interceptors.request.use(
  config => {
	if (localStorage.getItem('username')&&localStorage.getItem('token')) {
	      config.headers.username = localStorage.getItem('username');
		  config.headers.token =    localStorage.getItem('token');
	    }
	return config;
  },
  error => {
    return Promise.error(error)
  });

// 响应拦截器
axios.interceptors.response.use(function (response) {

  // if(localStorage.getItem('username')!='admin'){
  //   MessageBox.alert("登录失效","登录已失效，请重新登录",{
  //   	confirmButtonText:"跳转至登录",
  //   	callback:action=>{
  //   		window.location.href="/login"
  //   	}
  //   })

  // }
    //用户信息是否超时，重定向到登录页面
    if (response.data.code== '401'){
		MessageBox.alert("登录失效","登录已失效，请重新登录",{
			confirmButtonText:"跳转至登录",
			callback:action=>{
				window.location.href="/login"
			}
		})
    }


    return response
	}, function (error) {

    return Promise.reject(error)
});


/**
 * get方法，对应get请求
 */
export function get (url, params) {
  return new Promise((resolve, reject) => {
		var loadingInstance = Loading.service({
		    text:'^_^ Loading...',
		    spinner:'el-icon-loading',
		    customClass:'lb-loading-icon-cls',
		    background:'transparent'
		  });
    axios.get(url, {
      params: params
    }).then(res => {
      resolve(res.data)
			loadingInstance.close();
    }).catch(err => {
      reject(err.data)
			loadingInstance.close();
    })
  })
}
/**
 * post方法，对应post请求
 */
export function post (url, params) {
  return new Promise((resolve, reject) => {
		var loadingInstance = Loading.service({
		    text:'^_^ Loading...',
		    spinner:'el-icon-loading',
		    customClass:'lb-loading-icon-cls',
		    background:'transparent'
		  });

    axios.post(url, params)
      .then(res => {
        resolve(res.data)
				loadingInstance.close();
      })
      .catch(err => {
        reject(err.data)
				loadingInstance.close();
      })
  })
}
